package com.zhentao.service.impl;

import com.zhentao.file.config.MinioConfig;
import com.zhentao.file.config.MinioConfigProperties;
import com.zhentao.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author : mgh
 * @date : 2024-06-30 19:18
 * @effect : 当前类的作用是
 * @projectTeam :
 */
//@Service
@EnableConfigurationProperties(MinioConfigProperties.class)
@Import(MinioConfig.class)
public class FileStorageServiceImpl implements FileStorageService {
    @Resource
    private MinioConfigProperties minioConfigProperties;
    @Resource
    private MinioClient minioClient;
    /**
     * 上传html文件到minio里面
     *
     * @param fileName
     * @param inputStream
     * @return 地址
     */
    @SneakyThrows
    @Override
    public String uploadHtmlFile(String fileName, InputStream inputStream) {

        //sadffsddfs.png
        String fname = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        //2.执行上传操作  0上传的参数
        PutObjectArgs poa = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fname)
                .contentType("text/html")
                .stream(inputStream,inputStream.available(),-1)
                .build();

        //3. 执行上传才走  1 上传
        minioClient.putObject(poa);
        //获取地址
        String url = minioClient.getObjectUrl(poa.bucket(), poa.object());
        System.out.println(url);
        return url;
    }
    /**
     * 上传html文件到minio里面
     *
     * @param fileName
     * @param inputStream
     * @return 地址
     */
    @SneakyThrows
    @Override
    public String uploadPictureFile(String fileName, InputStream inputStream) {

        //sadffsddfs.png
        String fname = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

        //2. 设置上传参数
        PutObjectArgs poa = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fname)
                .contentType("image/jpeg")  // 根据实际图片格式设置 MIME 类型
                .stream(inputStream, inputStream.available(), -1)
                .build();
// 确保 bucket 存在
//3. 上传文件
        minioClient.putObject(poa);

// 获取文件 URL
        String url = minioClient.getObjectUrl(poa.bucket(), poa.object());
        System.out.println(url);
        return url;
    }
}
